import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'dart:io';

class MsgChannelPage extends StatefulWidget {
  @override
  _MsgChannelPageState createState() => new _MsgChannelPageState();
}

class _MsgChannelPageState extends State<MsgChannelPage> {

  late InAppWebViewController webController;

  @override
  void initState() {
    super.initState();
    _init();
  }

  _init() async {
    if (Platform.isAndroid) {
      await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
    }
  }
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    android: AndroidInAppWebViewOptions(
      useHybridComposition: true,
    ),);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text("Web Message Channels")),
          body: SafeArea(
              child: Column(children: <Widget>[
                Expanded(
                  child: InAppWebView(
                    initialData: InAppWebViewInitialData(
                        data: """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebMessageChannel Test</title>
</head>
<body>
    <!-- when you click this button, it will send a message to the Dart side -->
    <button id="button" onclick="port.postMessage(input.value);" />Send</button>
    <button id="button" onclick="toast()" />Toast</button>
    <br />
    <input id="input" type="text" value="JavaScript To Native" />
    
    <script>
      var port;
      window.addEventListener('message', function(event) {
          if (event.data == 'welfare-game' && event.ports[0] != null) {
              port = event.ports[0];
                  port.onmessage = function (event) {
                      console.log(event.data);
                      var jsonObject =  JSON.parse(event.data);
                      console.log(jsonObject.key);
                      console.log(jsonObject.value);
                  };
          }
      }, false);
      
      function toast(){
      port.postMessage('js发送给dart');
      }
      
      
    </script>
</body>
</html>
"""),
                    initialOptions: options,
                    onWebViewCreated: (controller){
                      webController = controller;
                      _dealChannel();
                    },
                    onConsoleMessage: (controller, consoleMessage) {
                      print("Message coming from the Dart side: ${consoleMessage.message}");
                    },
                    onLoadStop: (controller, url) {

                    },
                  ),
                ),
              ])
          )
      ),
    );
  }

  _dealChannel() async {
    if (!Platform.isAndroid || await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.CREATE_WEB_MESSAGE_CHANNEL)) {
    // wait until the page is loaded, and then create the Web Message Channel
    var webMessageChannel = await webController.createWebMessageChannel();
    var port1 = webMessageChannel!.port1;
    var port2 = webMessageChannel.port2;

    // set the web message callback for the port1
    await port1.setWebMessageCallback((message) async {
    print("from the JS: $message");
    // when it receives a message from the JavaScript side, respond back with another message.
    String key = "getLoginId";
    String value = '{"buttons":[{"index":0,"schemeUrl":"welfare-game://2011?needSecVerify=true","title":"去绑手机号"}],"closeBtnMarginTop":10,"closeBtnType":"clear","contentClickClose":true,"contentHtml":"要绑定手机号，才能做任务赚钱","contentStyle":"center","name":"兼职任务","titleHtml":"做任务赚钱需要绑定手机号"}';
    String msg = '{"key":"${key}","value":"${value}"}';
    await port1.postMessage(WebMessage(data: msg));
    });

    // transfer port2 to the webpage to initialize the communication
    await webController.postWebMessage(message: WebMessage(data: "welfare-game", ports: [port2]), targetOrigin: Uri.parse("*"));
    }
  }
}